package backpage.service.Impl;

import backpage.entity.Department;
import backpage.entity.Employee;
import backpage.entity.Department;
import backpage.exception.BusinessException;
import backpage.exception.ServiceException;
import backpage.mapper.DepartmentMapper;
import backpage.mapper.EmployeeMapper;
import backpage.service.DepartmentEmployeeService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class DepartmentEmployeeServiceImpl implements DepartmentEmployeeService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 根据部门ID生成用户ID
     * @param departmentId 部门ID（主键）
     * @return 生成的用户ID
     * @author 吴文钦
     */
    @Override
    public String createUserIdByDepartmentId(Integer departmentId) {
        // 根据部门ID查询部门信息
        Department department = departmentMapper.selectById(departmentId);
        if (department == null) {
            throw new IllegalArgumentException("部门ID不存在");
        }
        // 获取部门代码和历史员工编号
        String departmentCode = department.getDepartmentCode();
        Integer departmentHistoryStaffNumber = department.getDepartmentHistoryStaffNumber();
        // 将历史员工编号格式化为六位数（不足六位时前面补零）
        String formattedStaffNumber = String.format("%06d", departmentHistoryStaffNumber+1);
        // 生成用户ID
        String userId = departmentCode + formattedStaffNumber;
        // 更新部门信息
        departmentMapper.updateById(department);
        // 返回生成的用户ID
        return userId;
    }

    /**
     * 新增员工信息
     * @param employee 员工对象
     * @return 添加是否成功
     * @author 吴文钦
     */
    @Override
    @Transactional
    public boolean insertEmpInfo(Employee employee) {
        // 检查部门是否存在并锁定部门记录
        Department department = departmentMapper.selectById(employee.getDepartmentId());
        if (department == null) {
            throw new RuntimeException("部门不存在");
        }

        // 插入员工记录
        int insertResult = employeeMapper.insert(employee);
        if (insertResult != 1) {
            throw new RuntimeException("插入员工失败");
        }

        // 更新部门人数
        Integer departmentHistoryStaffNumber = department.getDepartmentHistoryStaffNumber();
        Integer departmentStaffNumber = department.getDepartmentStaffNumber();
        // 更新历史员工编号（加一）
        department.setDepartmentHistoryStaffNumber(departmentHistoryStaffNumber + 1);
        department.setDepartmentStaffNumber(departmentStaffNumber + 1);
        int updateResult = departmentMapper.updateById(department);
        if (updateResult != 1) {
            throw new RuntimeException("更新部门人数失败");
        }
        return true;
    }
    /**
     * 根据员工ID删除员工
     * @param employeeId 员工ID（主键）
     * @return 删除操作是否成功
     * @author 吴文钦
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteEmployeeById(Integer employeeId) {
        try {
            // 参数校验
            if (employeeId == null) {
                throw new BusinessException("员工ID不能为空");
            }

            // 查询员工
            Employee employee = employeeMapper.selectById(employeeId);
            if (employee == null) {
                throw new BusinessException("员工不存在");
            }

            // 获取部门ID
            Integer departmentId = employee.getDepartmentId();
            if (departmentId == null) {
                throw new BusinessException("员工未分配部门");
            }

            // 删除员工
            int deleteCount = employeeMapper.deleteById(employeeId);
            if (deleteCount == 0) {
                throw new BusinessException("员工删除失败");
            }

            // 原子更新部门人数
            int updateCount = departmentMapper.update(null,
                    new LambdaUpdateWrapper<Department>()
                            .setSql("department_staff_number = department_staff_number - 1")
                            .eq(Department::getDepartmentId, departmentId)
                            .gt(Department::getDepartmentStaffNumber, 0)
            );

            return true;
        } catch (BusinessException e) {
            throw e; // 透传业务异常
        } catch (DataAccessException e) {
            throw new ServiceException("系统繁忙，请稍后重试");
        } catch (Exception e) {
            throw new ServiceException("操作失败");
        }
    }
}
